package mine.code.question.动态规划;

import org.junit.Test;

/**
 * 给定三个字符串s1、s2、s3，请你帮忙验证s3是否是由s1和s2 交错 组成的。
 * <p>
 * 两个字符串 s 和 t 交错 的定义与过程如下，其中每个字符串都会被分割成若干 非空 子字符串：
 * <p>
 * s = s1 + s2 + ... + sn
 * <p>
 * t = t1 + t2 + ... + tm
 * <p>
 * |n - m| <= 1
 * <p>
 * 交错 是 s1 + t1 + s2 + t2 + s3 + t3 + ... 或者 t1 + s1 + t2 + s2 + t3 + s3 + ...
 * <p>
 * 提示：a + b 意味着字符串 a 和 b 连接。
 * <p>
 * 输入：s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
 * 输出：true
 *
 * @author caijinnan
 */
public class 交错字符串 {

    @Test
    public void run() {
        String s1 = "q";
        String s2 = "";
        String s3 = "c";
//        String s1 = "aabcc";
//        String s2 = "dbbca";
//        String s3 = "aadbbcbcac";
        System.out.println(isInterleave(s1, s2, s3));
    }

    // s1 = abcd
    // s2 = acdd
    // s3 = acabdcdd
    public boolean isInterleave(String s1, String s2, String s3) {

        // dp[i][j][i+j] = dp[i-1][j][k-1]&&s1.i==s3.k || dp[i][j-1][k-1]&&s2.j==s3.k
        int s1Length = s1.length();
        int s2Length = s2.length();
        int s3Length = s3.length();
        if (s1Length + s2Length != s3Length) {
            return false;
        }
        boolean[][][] dp = new boolean[s1Length + 1][s2Length + 1][s3Length + 1];
        dp[0][0][0] = true;
        for (int i = 0; i < s1Length; i++) {
            dp[i + 1][0][i + 1] = dp[i][0][i] && (s1.charAt(i) == s3.charAt(i));
        }
        for (int i = 0; i < s2Length; i++) {
            dp[0][i + 1][i + 1] = dp[0][i][i] && (s2.charAt(i) == s3.charAt(i));
        }

        for (int i = 0; i < s1Length; i++) {
            for (int j = 0; j < s2Length; j++) {
                char s1Char = s1.charAt(i);
                char s2Char = s2.charAt(j);
                int k = i + j;
                char s3Char = s3.charAt(k + 1);
                if (s1Char == s3Char && s2Char == s3Char) {
                    dp[i + 1][j + 1][k + 2] = dp[i][j + 1][k + 1] || dp[i + 1][j][k + 1];
                } else if (s1Char == s3Char) {
                    dp[i + 1][j + 1][k + 2] = dp[i][j + 1][k + 1];
                } else if (s2Char == s3Char) {
                    dp[i + 1][j + 1][k + 2] = dp[i + 1][j][k + 1];
                }
            }
        }
        return dp[s1Length][s2Length][s3Length];
    }
}
